<?php

namespace app\api\controller;
use Throwable;
use think\facade\Db;
use think\facade\Request;
use app\admin\model\Admin;
use app\admin\model\UserVip;
use app\admin\model\User as UserModel;
use app\api\service\userService;
use app\api\validate\Admin as AdminValidate;
use app\common\controller\Api;
use EasyWeChat\MiniApp\Application;
use app\common\library\Upload;
use EasyWeChat\Pay\Application as payApp;
class User extends Api
{ 
    /**
     * 修改密码
     * author：mozi
     * time:2025.05.17
     * */
	function changePwd(){
         $params = $this->request->post("");
         $pwd = $params['pwd'] ?? '';
         $code = $params['mess_code'] ?? '';
         if(trim($pwd) == '' || trim($code) == ''){
              return json(['code'=>100,'msg'=>'密码和短信验证码不能为空']);
         }

         return json(['code'=>200,'msg'=>'ok']);

    } 
    //申请提现
    function withdrawal(){
         $params = $this->request->post("");
         $money = $params['money'] ?? 0;
         
         if(trim($money) == '' || trim($money) == 0){
              return json(['code'=>100,'msg'=>'请输入提现金额']);
         }
         // 获取中间件设置的 userId
         $admin_id = request()->adminId;
         $balance = Admin::where("id",$admin_id)->value("balance");
         if($balance < $money){
              return json(['code'=>100,'msg'=>'余额不足，无法提现！']);
         }
         $r = userService::withdrawal(request()->userId,$money,request()->adminId);
          
         return json(['code'=>$r['code'],'msg'=>$r['msg']]);
    }

    //提现记录
    function withdrawalRecord(){
            $userId = request()->adminId;
            $page = $this->request->post("page",1);
            $res = userService::withdrawalRecord($page,$userId);
            return json(['code'=>200,'msg'=>'ok','data'=>$res['data'] ?? [],'total'=>$res['total']]);
    }

    //用户信息
    function info(){
        $res = UserModel::where("id",request()->userId)->field("id,wx_name,mobile,money,score")->find();
        return json(['code'=>200,'msg'=>'ok','data'=>$res ?? []]);
    }
    //用户充值
    function recharge(){
         $params = $this->request->post("");
         $userId = request()->userId;
         $r = userService::rechargeOrder($userId,$params);
         return json(['code'=>$r['code'],'ordernum'=>$r['ordernum'],'msg'=>'ok']);
    }

    //用户充值记录
    function rechargeRecord(){
         $userId = request()->userId;
         $res = userService::rechargeRecord($userId);
         return json(['code'=>200,'data'=>$res,'msg'=>'ok']);
    }


    //授权获取手机号

    function getPhone(){

        $phone_code = $this->request->param('code');
        if ($phone_code) {
            // 创建微信小程序对象
            $wechat = new Application($this->getConfig());
            // getPhoneNumber
            $data = ['code' => $phone_code];

            try {
                      $result = $wechat->getClient()->postJson('wxa/business/getuserphonenumber', $data);
                      if (isset($result['phone_info'])) {
                          // 业务处理
                          $userId = request()->userId;
                                  $this->success($userId.'==');
                          $r  = UserModel::where("id",$userId)->update(['mobile'=>$result['phone_info']]);
                          return json(['code' =>$r?200:100, 'msg' => $r ? 'ok' : '失败']);
                      } else {
                          // 报错 $res['errmsg']
                          return json(['code' => 100, 'data' => '', 'msg' => $result['errmsg']]);
                      }
            }catch (Throwable $e) {
                   $this->error($e->getMessage());
            }

        }else{
            return json(['code' => 100, 'msg' => 'code lost !']);
        }
 
    }



     /**
     * 附件上传
     * author：mozi
     * time:2025.05.16
     * */
    public function upload(): void
    {
        $file   = $this->request->file('file');
        $driver = $this->request->param('driver', 'local');
        $topic  = $this->request->param('topic', 'default');
         
        try {
            $upload = new Upload();
            $attachment = $upload
                ->setFile($file)
                ->setDriver($driver)
                ->setTopic($topic)
                ->upload(null, 0, 2);
            unset($attachment['create_time'], $attachment['quote']);
        }catch (Throwable $e) {
            $this->error($e->getMessage());
        }
        $attachment['full_url'] = 'http:'.$attachment['full_url'];
        $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }
}